<script lang="ts" setup>
import { IRole, roleModel } from '@/api/system/role';
import { FormConfig } from '@/components/Form/types';
import { NInput, NSelect } from 'naive-ui';
import { computed, ref, unref } from 'vue';
import MenuSelectTree from '@/components/MenuSelectTree/index.vue';

interface Props {
  data: Partial<IRole>
}
const props = withDefaults(defineProps<Props>(), {
  data: () => ({
    status: 1
  })
}) ;
const emits = defineEmits(['close', 'submit']);
const formData = ref<Partial<IRole>>({
  ...props.data
});

const config = computed<FormConfig<typeof formData.value>[]>(() => [
  {
    type: 'component',
    label: '角色名称:',
    component: NInput,
    key: 'roleName',
    itemProps: {
      rule: [
        { required: true, validator(rule, value) {
          if(!value) {
            return new Error('请输入角色名称');
          }
          return true;
        }, trigger: 'blur' }
      ]
    }
  },
  {
    type: 'component',
    label: '角色状态:',
    component: NSelect,
    key: 'status',
    props: {
      options: [
        { label: '正常', value: 1 },
        { label: '停用', value: 0 }
      ]
    },
    itemProps: {
      rule: [
        { required: true, validator(rule, value) {
          if(value !== 0 && !value) {
            return new Error('请选择角色状态');
          }
          return true;
        }, trigger: 'blur' }
      ]
    }
  },
  {
    type: 'component',
    label: '角色权限:',
    component: MenuSelectTree,
    key: 'menuIds',
    listeners: {
      selected: (data) => {
        formData.value.menuIds = data.join(',');
        console.log('selected==>', data);
      }
    }
  },
  {
    type: 'slot',
    slotName: 'submit'
  }
]);
const roleUpgradeForm = ref();
async function submit() {
  await roleUpgradeForm.value.validate();
  const params = {
    ...unref(formData)
  };
  await roleModel.upgrade(params);
  emits('submit');
}
</script>
<template>
  <div>
    <Form
      ref="roleUpgradeForm"
      v-model:data="formData"
      :label-width="90"
      :config="config"
    >
    <template #submit>
        <div class="flex justify-end gap-mini">
          <NButton @click="emits('close')">
            取消
          </NButton>
          <NButton type="primary" @click="submit">
            确定
          </NButton>
        </div>
      </template>
    </Form>
  </div>
</template>
